package live.ifox.stage;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.SparseBooleanArray;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import live.ifox.base.BaseRestActivity;
import live.ifox.factory.Entry;
import live.ifox.factory.ID;
import live.ifox.factory.Url;
import live.ifox.helper.AdapterHelper;
import live.ifox.helper.CommonHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ContactActivity extends BaseRestActivity {
    Spinner sp_province, sp_city;
    List<String> provinces, cities;
    SwipeRefreshLayout swipeLayout;
    ListView listView;
    JSONArray array;
    String selectProvince, selectCity;
    boolean choiceMode;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_contact);

        choiceMode = false;
        entry = Entry.MedicalContact;
        baseUrl = Url.MedicalContact;
        listView = findViewById(R.id.listView);
        registerForContextMenu(listView);
        if (getIntent().hasExtra("choice")) {
            choiceMode = true;
            listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        }

        sp_province = findViewById(R.id.province);
        sp_province.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectProvince = provinces.get(position);
                updateCity();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        sp_city = findViewById(R.id.city);
        sp_city.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                selectCity = cities.get(position);
                updateView();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        swipeLayout = findViewById(R.id.swipeLayout);
        swipeLayout.setOnRefreshListener(() -> {
            swipeLayout.setRefreshing(false);
            updateView();
        });

        updateProvince();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (!choiceMode) {
            menu.add(0, ID.ACTION_ADD, 0, "添加...");
            menu.add(0, ID.ACTION_UPDATE_CITY, 1, "更新城市");
            menu.add(0, ID.ACTION_UPDATE_PROVINCE, 2, "更新省份");
        } else {
            menu.add(0, ID.ACTION_BATCH_ADD, 0, "添加所选");
            menu.add(0, ID.ACTION_CLEAN, 1, "清空所选");
        }
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case ID.ACTION_ADD:
                startActivity(new Intent(this,
                        ContactEditor.class));
                return true;
            case ID.ACTION_UPDATE_CITY:
                updateCity();
                return true;
            case ID.ACTION_UPDATE_PROVINCE:
                updateProvince();
                return true;
            case ID.ACTION_BATCH_ADD:
                do_batchAddDial();
                return true;
            case ID.ACTION_CLEAN: {
                if (listView.getCheckedItemCount() > 0)
                    listView.clearChoices();
                updateView();
            }
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        if (choiceMode)
            return;

        menu.add(0, ID.ACTION_EDIT, 0, "编辑...");
        menu.add(0, ID.DIAL_EDITOR, 1, "添加到计划");
        menu.add(0, ID.ACTION_REMOVE, 2, "删除");
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (array == null || array.isEmpty() || choiceMode)
            return false;

        AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
        int position = info.position;
        JSONObject object = array.getJSONObject(position);
        if (object == null || object.isEmpty())
            return false;

        switch (item.getItemId()) {
            case ID.ACTION_EDIT:
                return do_editItem(object);
            case ID.DIAL_EDITOR:
                return do_addItemDial(object);
            case ID.ACTION_REMOVE:
                return do_removeItem(object);
        }
        return super.onContextItemSelected(item);
    }

    // 批量插入
    void do_batchAddDial() {
        if (!choiceMode ||
                listView.getCheckedItemCount() == 0)
            return;

        if (listView.getCheckedItemCount() > 10) {
            listView.clearChoices();
            CommonHelper.showMessage(this, "单次添加不能超过10条！");
            return;
        }

        SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
        for (int i = 0; i < checkedItems.size(); i++) {
            JSONObject object = array.getJSONObject(checkedItems.keyAt(i));
            String name = object.getString("name");
            String phone = object.getString("phone");
            String remark = object.getString("remark");
            if (name.isEmpty() || phone.isEmpty())
                continue;

            Map<String, String> item = new HashMap<>();
            item.put("name", name);
            item.put("phone", phone);
            item.put("remark", remark);
            httpPost(Url.MedicalDial + "insert", JSON.toJSONString(item));
        }
        new Handler().postDelayed(() ->
        {
            setResult(ID.RESULT_DONE);
            finish();
        }, 100 * checkedItems.size());
    }

    boolean do_addItemDial(JSONObject object) {
        String name = object.getString("name");
        String phone = object.getString("phone");
        String remark = object.getString("remark");
        if (name.isEmpty() || phone.isEmpty())
            return false;

        Map<String, String> item = new HashMap<>();
        item.put("name", name);
        item.put("phone", phone);
        item.put("remark", remark);

        httpPost(Url.MedicalDial + "insert", JSON.toJSONString(item));
        CommonHelper.showMessage(this, "已添加到计划列表");
        return true;
    }

    boolean do_editItem(JSONObject object) {
        int id = object.getIntValue("id");
        String province = object.getString("province");
        String city = object.getString("city");
        String name = object.getString("name");
        String phone = object.getString("phone");
        String remark = object.getString("remark");
        if (id == 0 || name.isEmpty() || phone.isEmpty())
            return false;

        Intent intent = new Intent(this,
                ContactEditor.class);
        intent.putExtra("id", id);
        intent.putExtra("province", province);
        intent.putExtra("city", city);
        intent.putExtra("name", name);
        intent.putExtra("phone", phone);
        intent.putExtra("remark", remark);
        startActivityForResult(intent, ID.CONTACT_EDITOR);
        return true;
    }

    void updateProvince() {
        httpGet(baseUrl + "get_provinces");
    }

    void updateCity() {
        if (selectProvince != null && !selectProvince.isEmpty())
            httpGet(baseUrl + "get_cities/" + selectProvince);
    }

    void updateView() {
        if (selectCity != null && !selectCity.isEmpty()) {
            httpGet(baseUrl + "by_city/" + selectCity);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == ID.RESULT_DONE) {
            updateView();
        }
    }

    @Override
    public void processReply(JSONObject rootObject) {
        if (rootObject.containsKey("provinces")) {
            JSONArray array = rootObject.getJSONArray("provinces");
            provinces = array.toJavaList(String.class);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_dropdown_item);
            adapter.addAll(provinces);
            sp_province.setAdapter(adapter);
        } else if (rootObject.containsKey("cities")) {
            JSONArray array = rootObject.getJSONArray("cities");
            cities = array.toJavaList(String.class);
            ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                    android.R.layout.simple_spinner_dropdown_item);
            adapter.addAll(cities);
            sp_city.setAdapter(adapter);
        } else if (rootObject.containsKey("detail")) {
            array = rootObject.getJSONArray("detail");
            if (array.isEmpty()) {
                listView.setAdapter(null);
                return;
            }

            if (choiceMode) {
                List<String> items = new ArrayList<>();
                for (int i = 0; i < array.size(); i++) {
                    JSONObject object = array.getJSONObject(i);
                    String item = object.getString("name") + "  " +
                            object.getString("phone") + "  " +
                            object.getString("remark");
                    items.add(item);
                }
                if (items.isEmpty())
                    return;
                ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
                        android.R.layout.simple_list_item_multiple_choice, items);
                listView.setAdapter(adapter);
            } else {
                List<Map<String, Object>> model = new ArrayList<>();
                for (int i = 0; i < array.size(); i++) {
                    JSONObject object = array.getJSONObject(i);
                    Map<String, Object> item = new HashMap<>();
                    item.put("name", object.getString("name"));
                    String detail = object.getString("phone") + "  " +
                            object.getString("remark");
                    item.put("detail", detail);
                    model.add(item);
                }
                if (model.isEmpty())
                    return;
                SimpleAdapter adapter = AdapterHelper.getTableAdapter(this, model,
                        new String[]{"name", "detail"});
                listView.setAdapter(adapter);
            }
        } else if (rootObject.containsKey("removed")) {
            updateView();
        }
    }
}
